<?php
namespace App\Admin\Controllers\Products;

use App\Importer\Products\SkuSupplier\SkuSupplierImporter;
use App\Models\Basics\Supplier;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\Product\ProductSupplier;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class SkuSupplierUploadController extends AdminController{

    protected $title = '产品供应商上传';

    protected function grid()
    {
        $type = request('type');
        return view("products.sku-supplier.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importSkuSupplier(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuSupplierImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $skuSArr = [];
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $supplierCode = $row[1] ? trim($row[1]) : '';
                $moq = $row[2] ? trim($row[2]) : '';
                $supplierPrice = $row[3] ? trim($row[3]) : '';
                $unitPrice = $row[4] ? trim($row[4]) : '';
                $purchaseCycle = $row[5] ? trim($row[5]) : '';
                $status = $row[6] ? trim($row[6]) : '否';
                if(!$sku || !$supplierCode || !$moq || !$supplierPrice || !$unitPrice || !$purchaseCycle){
                    $errors[$count] = '新增时前六项为必填项';
                    continue;
                }
                $key = $sku.'_'.$supplierCode;
                if(!in_array($key,$skuSArr)){
                    $skuSArr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!in_array($status,ProductSupplier::$_status)){
                    $errors[$count] = $status.'状态不存在，请选择'.implode('、',ProductSupplier::$_status);
                    continue;
                }
                $ps = ProductSku::getModelByCode($sku);
                if(!$ps){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                if($ps->is_mix == 1){
                    $errors[$count] = $sku.'组合产品无需添加供应商';
                    continue;
                }
                $supplierId = Supplier::getIdByCode($supplierCode,false);
                if(!$supplierId){
                    $errors[$count] = '供应商编码不存在或未审核或已停用';
                    continue;
                }
                $reCount = ProductSupplier::query()
                    ->where('psku_id',$ps->id)
                    ->where('supplier_id',$supplierId)
                    ->count();
                if($reCount > 0){
                    $errors[$count] = $key.'系统已存在，需要更新请前往更新';
                    continue;
                }
                DB::beginTransaction();
                $pSupplier = ProductSupplier::query()->create(
                    [
                        'psku_id' => $ps->id,
                        'supplier_id' => $supplierId,
                        'moq' => $moq,
                        'supplier_price' => $supplierPrice,
                        'unit_price' => $unitPrice,
                        'purchase_cycle' => $purchaseCycle,
                        'status' => array_search($status,ProductSupplier::$_status),
                    ]
                );
                if($pSupplier){
                    if($pSupplier->status == 1){
                        ProductSupplier::modifyDefaultPuSupplier($pSupplier->id,$pSupplier->psku_id);
                    }
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    private function _importSkuSupplierUp(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuSupplierImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $skuSArr = [];
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $supplierCode = $row[1] ? trim($row[1]) : '';
                $moq = $row[2] ? trim($row[2]) : '';
                $supplierPrice = $row[3] ? trim($row[3]) : '';
                $unitPrice = $row[4] ? trim($row[4]) : '';
                $purchaseCycle = $row[5] ? trim($row[5]) : '';
                $status = $row[6] ? trim($row[6]) : '';
                if(!$sku || !$supplierCode){
                    $errors[$count] = '更新时前两项为必填项';
                    continue;
                }
                $key = $sku.'_'.$supplierCode;
                if(!in_array($key,$skuSArr)){
                    $skuSArr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                $supplierId = Supplier::getIdByCode($supplierCode,false);
                if(!$supplierId){
                    $errors[$count] = '供应商编码不存在或未审核或已停用';
                    continue;
                }
                DB::beginTransaction();
                $pSupplier = ProductSupplier::query()
                    ->where('psku_id',$pSkuId)
                    ->where('supplier_id',$supplierId)
                    ->first();
                if(!$pSupplier){
                    $errors[$count] = $key.'系统不存在，需要新增请前往新增';
                    DB::rollBack();
                    continue;
                }
                if($status){
                    if(!in_array($status,ProductSupplier::$_status)){
                        $errors[$count] = $status.'状态不存在，请选择'.implode('、',ProductSupplier::$_status);
                        DB::rollBack();
                        continue;
                    }
                    $pSupplier->status = array_search($status,ProductSupplier::$_status);
                }
                if($moq){
                    $pSupplier->moq = $moq;
                }
                if($supplierPrice){
                    $pSupplier->supplier_price = $supplierPrice;
                }
                if($unitPrice){
                    $pSupplier->unit_price = $unitPrice;
                }
                if($purchaseCycle){
                    $pSupplier->purchase_cycle = $purchaseCycle;
                }
                $flag = $pSupplier->save();
                if($flag){
                    if($pSupplier->status == 1){
                        ProductSupplier::modifyDefaultPuSupplier($pSupplier->id,$pSupplier->psku_id);
                    }
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    private function _importSkuSupplierCycle(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuSupplierImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $skuSArr = [];
            foreach($data as $row){
                $count++;
                $classify = $row[0] ? trim($row[0]) : '';
                $cycle = $row[1] ? trim($row[1]) : '';
                if(!$classify || !$cycle){
                    $errors[$count] = '必填项为空或0';
                    continue;
                }
                if(!in_array($classify,$skuSArr)){
                    $skuSArr[$count] = $classify;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $classifyId = ProductClassify::getIdByTitle($classify);
                if(!$classifyId){
                    $errors[$count] = $classify.'系统不存在';
                    continue;
                }
                $pSkuIds = ProductSku::query()
                    ->where('classify_id',$classifyId)
                    ->pluck('id')
                    ->toArray();
                if(!$pSkuIds){
                    $errors[$count] = '品类:'.$classify.'无产品';
                    continue;
                }
                DB::beginTransaction();
                ProductSupplier::query()
                    ->whereIn('psku_id',$pSkuIds)
                    ->where('status',1)
                    ->update(['purchase_cycle' => $cycle]);
                DB::commit();
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
